package notifyandwait;

import java.io.Serializable;
import java.util.Objects;

/**
 * Created by 5406160@qq.com on LiBoWen 李博闻.
 *
 * @ClassName : Customer
 * @Author : 54061
 * @Date: 2022/2/15 18:46
 */
/*
Customer 除了是线程类之外还在描述顾客事物
 */
public class Customer extends Thread implements Serializable {
    private static final long serialVersionUID = -1383979456799282517L;
    //包子属性
    private BaoZi bz;

    public Customer() {
    }

    public Customer(String name) {
        super(name);
    }

    public Customer(BaoZi bz) {
        this.bz = bz;
    }

    public Customer(String name, BaoZi bz) {
        super(name);
        this.bz = bz;
    }

    public BaoZi getBz() {
        return bz;
    }

    public void setBz(BaoZi bz) {
        this.bz = bz;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Customer customer = (Customer) o;
        return Objects.equals(bz, customer.bz);
    }

    @Override
    public int hashCode() {
        return Objects.hash(bz);
    }

    @Override
    public void run() {
        //顾客线程需要完成的任务
        //假设顾客一直吃
        while (true){
            //加锁
            synchronized (bz){
                //说明时候顾客要休眠
                if (!bz.isFlag()){
                    //没有包子,顾客就不能执行
                    try {
                    //无限等待,顾客线程就释放锁资源和cpu资源 不能继续执行了!!!
                        bz.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                //如果能下来 说明有包子 bz的状态是true
                //吃包子
                System.out.println("姓名是"+getName()+"的顾客正在吃"+bz.getXianer()+"的包子");
                //吃包子花了3秒钟
                try {
                    Thread.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("包子真好吃 我还要吃 老板在来一份");
                System.out.println("------------");
                //真正的吃包子代码
                bz.setFlag(false);
                //唤醒厨师线程
                bz.notify();
            }
        }

    }
}
